#  daemon_launcher.rb
#
#  This file is part of myvnet.
#
#  Copyright (C) 2008  Filipe David Borba Manana,  fdmanana@gmail.com
#
#  myvnet is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  myvnet is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with myvnet.  If not, see <http://www.gnu.org/licenses/>.


require 'singleton'
require 'lib/daemon_registry'
require 'lib/daemon_dispatcher'
require 'lib/daemons/ping_daemon'
require 'lib/daemons/arp_daemon'
require 'lib/config'
require 'lib/utils'
require 'lib/exceptions'
require 'lib/packet/sniffer'
require 'lib/packet/injector'


module Daemon
  
  # Registers daemons, starts the daemon dispatcher and a packet sniffer.
  #
  class Launcher
    include Singleton
    
    def initialize
      @conf = Config::Settings.instance
      hwaddr = Utils.iface_hwaddr(@conf.interface)
      
      unless hwaddr
        msg = "Could not get the hardware address of the network interface"
        msg << " `#{@conf.interface}'"
        $log[:stderr].fatal msg
        exit 1
      end
      
      @dreg = Daemon::Registry.instance
      @ddisp = Daemon::Dispatcher.instance
                        
      begin
        @sniffer = Packet::Sniffer.new(@conf.interface)
      rescue RootUserError
        $log[:stderr].fatal "myvnet requires root user privileges"
        exit 1
      rescue SnifferError => ex
        $log[:stderr].fatal "Could not start packet sniffer: #{ex.message}"
        exit 1
      end
            
      pkt_inj = Packet::Injector.new(@conf.interface)

      # registration of daemons
      pingd = Daemon::PingDaemon.new("PingDaemon", pkt_inj, 
                                     hwaddr, *@conf.net_addresses)
      @dreg.register pingd
      @sniffer.add_filter pingd.packet_filter
      
      arpd = Daemon::ArpDaemon.new("ArpDaemon", pkt_inj,
                                   hwaddr, *@conf.net_addresses)
      @dreg.register arpd
      @sniffer.add_filter arpd.packet_filter
      #
      
    end
    
    
    def start
      
      begin
        @sniffer.each_packet do |packet|
          @ddisp.add_packet packet
        end
      rescue Interrupt
        @sniffer.stop
        $log[:stdout].info "myvnet stopped."  
        exit 0
      end
      
    end
    
  end
  
end
